package org.jaaksi.kottlindemo.dao

import android.util.Log
import org.jaaksi.greendao.gen.DaoSession
import org.jaaksi.greendao.gen.NoteDao
import org.jaaksi.greendao.gen.UserDao
import org.jaaksi.kottlindemo.dao.model.UserBean
import org.jaaksi.kottlindemo.dao.model.db.*
import java.util.concurrent.Callable
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class DbUtil @Inject constructor(private val daoSession: DaoSession) {

    // 开启事务
    fun <V> callInTx(callable: Callable<V>) {
        daoSession.callInTx(callable)
    }

    fun addUser(user: User): Long {
        return daoSession.userDao.insertOrReplace(user)
    }

    fun addNote(note: Note): Long {
        return daoSession.noteDao.insertOrReplace(note)
    }

    fun getUserList(): MutableList<User>? {
        return daoSession.userDao.queryBuilder().build().list()
    }

    fun getUserByCode(userCode: String): UserBean? {
        // 连表查询：select a.xx1,a.xx2,b.xx,c.xx from $tableName1 as a join $tableName2 as b join $tableName3 as c where a.xx1 = b.xx and a.xx1 = c.xx and a.xx1 = $value order by a.xx1 asc
        val sql =
            "select a.${UserDao.Properties.Usercode.columnName},a.${UserDao.Properties.Name.columnName},b.${NoteDao.Properties.Note.columnName},b.${NoteDao.Properties.UserCode.columnName} from ${UserDao.TABLENAME} as a join ${NoteDao.TABLENAME} as b where a.${UserDao.Properties.Usercode.columnName} = $userCode and b.${NoteDao.Properties.UserCode.columnName} = a.${UserDao.Properties.Usercode.columnName}"
        Log.d("greenDAO", "getUserByCode: sql = $sql")
//        val list = daoSession.userDao.queryBuilder().apply {
//            join(Note::class.java, NoteDao.Properties.Note)
//                .whereOr(
//                    UserDao.Properties.Usercode.eq("1001"),
//                    NoteDao.Properties.UserCode.eq("1001")
//                )
//        }.build().list()

        val cursor = daoSession.database.rawQuery(sql, null)
        while (cursor?.moveToNext() == true) {
            val userCode =
                cursor.getString(cursor.getColumnIndex(UserDao.Properties.Usercode.columnName))
            val name =
                cursor.getString(cursor.getColumnIndex(UserDao.Properties.Name.columnName))
//            val noteCode =
//                cursor.getString(cursor.getColumnIndex(NoteDao.Properties.UserCode.columnName))
            val note = cursor.getString(cursor.getColumnIndex(NoteDao.Properties.Note.columnName))
            return UserBean(userCode, name, note)
        }
        return null
    }
}